<?php
defined('IN_APPS') or die('Go away...');

require_once MODEL_PATH . DS . 'group_model.php';

class Group extends Controller {
	
	public function index()
	{
		global $view;
		
		$view->assign('title', 'Group List');
		
		// create instance
		$groupModel = new GroupModel();
		
		$groups = $groupModel->getAll();
		
		$view->assign('groups', $groups);
		
		$view->display('group.index.php');
	}
	
	
	public function add()
	{
		global $view;
		
		$view->assign('title', 'Add New Group');
		
		$view->display('group.add.php');
	}
	
	
	public function del($id)
	{
		$groupModel = new GroupModel();
		
		if ($groupModel->del($id)) {
			redirect(
					array(
						'controller'	=> 'group',
						'action'		=> 'index'
					), 'Group deleted!');
		}
		else {
			redirect(
					array(
						'controller'	=> 'group',
						'action'		=> 'index'
					), 'Error deleting group!', 'error');
		}
	}


	/**
	 * Show edit user form
	 */	 	
	public function edit($id)
	{
		// load smarty from our global variable
		global $view;
		
		// create UserModel instance
		$groupModel = new GroupModel();
		
		// get user details so we can populate it in our form
		$group = $groupModel->get($id);
		
		// assign it to our view
		$view->assign('group', $group);
		
		// set page title
		$view->assign('title', 'Edit Group : ' . $this->title);
		
		// load the view file
		$view->display('group.edit.php');
	}	
	
	
	/**
	 * Create new user
	 */
	public function update()
	{
		$security = new Security();
		
		// get all data from our user.add.php
		$id					= $_POST['id'];
		$data['name']		= $security->xss_clean($_POST['name']);
		
		// create GroupModel instance
		$groupModel = new GroupModel();
		
		// call method to save the user
		if ($groupModel->update($id, $data)) {
			// user successfully created
			redirect(array('controller' => 'group', 'action' => 'index'), 'Group information have been updated.', 'notice');
		}
		else {
			// opsss.. something went wrong here..
			redirect(array('controller' => 'group', 'action' => 'edit'), 'Error updating group!', 'error');
		}
	}	
	
	
	public function create()
	{
		$security = new Security();
		
		$data['name']	= $security->xss_clean($_POST['name']);
		
		if (empty($data['name']) OR $data['name'] == '') {
			redirect(array('controller' => 'group', 'action' => 'add'), 'Group name is empty!', 'error');
		}
		
		// create new instance GroupModel
		$groupModel = new GroupModel();
		
		if ($groupModel->create($data)) {
			// if save success
			redirect(array('controller' => 'group', 'action' => 'index'), 'Group saved');
		}
		else {
			// error
			redirect(array('controller' => 'group', 'action' => 'add'), 'Cannot save group', 'error');
		}
		
	}	
	
}
